import Taro from '@tarojs/taro-rn';
import * as tslib_1 from "tslib";
import React from 'react';
import { Component } from "@tarojs/taro-rn";
import { toJS } from "mobx";
import { ScrollView, View, Text, Image } from "@tarojs/components-rn";
import { getRuntime, pageSize } from "../../utils/common";
import indexStyleSheet from "./index_styles";
import { inject, observer } from "@tarojs/mobx-rn";
var _styleSheet = indexStyleSheet;

function _getClassName() {
  var className = [];
  var args = arguments[0];
  var type = Object.prototype.toString.call(args).slice(8, -1).toLowerCase();

  if (type === 'string') {
    args = args.trim();
    args && className.push(args);
  } else if (type === 'array') {
    args.forEach(function (cls) {
      cls = _getClassName(cls).trim();
      cls && className.push(cls);
    });
  } else if (type === 'object') {
    for (var k in args) {
      k = k.trim();

      if (k && args.hasOwnProperty(k) && args[k]) {
        className.push(k);
      }
    }
  }

  return className.join(' ').trim();
}

function _getStyle(classNameExpression) {
  var className = _getClassName(classNameExpression);

  var classNameArr = className.split(/\s+/);
  var style = [];

  if (classNameArr.length === 1) {
    style.push(_styleSheet[classNameArr[0].trim()]);
  } else {
    classNameArr.forEach(function (cls) {
      style.push(_styleSheet[cls.trim()]);
    });
  }

  return style;
}

let Index = class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      totalCount: 0,
      areasOfExpertise: [],
      allProvince: [],
      allCity: [],
      allDistrict: [],
      provinceId: -1,
      cityId: -1,
      districtId: -1,
      labelId: null,
      pageIndex: 1,
      pageSize
    };
  }
  componentWillMount() {
    Taro.setNavigationBarTitle({ title: '律政中心' });
    this.getAllProvince();
    this.getAllCity();
    this.getAllDistract();
    this.getAreasOfExpertise();
    this.getAllLawyerInfo();
  }
  getAllProvince() {
    let { AreaStore } = this.props.stores;
    AreaStore.getAllProvinceFromLocal({
      callBack: res => {
        this.setState({
          allProvince: res
        });
      }
    });
  }
  getAllCity(index = -1) {
    let { AreaStore } = this.props.stores;
    AreaStore.getAllCityFromLocal({
      index,
      callBack: res => {
        this.setState({
          allCity: res
        });
      }
    });
  }
  getAllDistract(indexProvince = -1, indexCity = -1) {
    let { AreaStore } = this.props.stores;
    AreaStore.getAllDistractFromLocal({
      indexProvince,
      indexCity,
      callBack: res => {
        this.setState({
          allDistrict: res
        });
      }
    });
  }
  // 获取所有标签
  getAreasOfExpertise() {
    const { stores: { LegalStore } } = this.props;
    LegalStore.getAreasOfExpertise({
      callback: res => {
        this.setState({
          areasOfExpertise: toJS(res.items)
        });
      }
    });
  }
  // 获取所有律师列表
  getAllLawyerInfo() {
    let { allProvince, allCity, allDistrict, provinceId, cityId, districtId, pageIndex, pageSize, labelId } = this.state;
    const { stores: { LegalStore } } = this.props;
    console.log('cityID:' + cityId);
    LegalStore.getAllLawyerInfo({
      formProvinceId: provinceId !== -1 ? allProvince[provinceId]['value'] : null,
      formCityId: cityId !== -1 ? allCity[cityId]['value'] : null,
      formDistrictId: districtId !== -1 ? allDistrict[districtId]['value'] : null,
      formAreasOfExpertiseId: labelId,
      pageIndex,
      pageSize,
      callback: res => {
        let resArr = toJS(res);
        // 转换擅长领域
        resArr.items.map(item => {
          return item.areaName = this._getAreaNameById(item.areasOfExpertise);
        });
        if (pageIndex === 1) {
          this.setState({ totalCount: toJS(res.totalCount), items: toJS(res.items)
          });
        } else {
          const { items } = this.state;
          items.push(...(res.items || []));
          this.setState({ totalCount: res.totalCount, items
          });
        }
      }
    });
  }
  onReachBottom() {
    let { totalCount, pageSize, pageIndex } = this.state;
    const { loading } = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getAllLawyerInfo();
      });
    }
  }
  // 根据标签ID获取标签值
  _getAreaNameById(ids) {
    let value = [];
    let AreasOfExpertise = this.state.areasOfExpertise;
    // let idArr = ids.split(',').filter(item => parseInt(item))
    AreasOfExpertise.map(item => {
      if (ids.includes(item['id'])) {
        value.push({
          id: item['id'],
          title: item['areaName']
        });
      }
    });
    // console.log(value)
    return value;
  }
  handelRouter(url = '/pages/index/index') {
    getRuntime().navigateTo(url);
  }
  /**
   * @param type
   * @param column  [0:省,1:市,2:区]
   * @param value 对应省市区的索引值
   */
  changeOption(type, column, value) {
    let { allProvince, allCity, allDistrict } = this.state;
    console.log(value);
    if (column === 0) {
      this.getAllCity(value);
      this.getAllDistract(value, 0);
      let cityId = value === -1 ? -1 : 0;
      let districtId = value === -1 ? -1 : 0;
      this.setState({
        [type]: value,
        cityId,
        districtId
      }, () => {
        this.getAllLawyerInfo();
      });
    } else if (column === 1) {
      this.getAllDistract(this.state.provinceId, value);
      let districtId = value === -1 ? -1 : 0;
      this.setState({
        [type]: value,
        districtId
      }, () => {
        this.getAllLawyerInfo();
      });
    } else {
      this.setState({
        [type]: value
      }, () => {
        this.getAllLawyerInfo();
      });
    }
  }
  changeLabel(id) {
    this.setState({
      labelId: id
    }, () => {
      this.getAllLawyerInfo();
    });
  }
  render() {
    let { items, allProvince, allCity, allDistrict, areasOfExpertise, provinceId, cityId, districtId, labelId } = this.state;
    let item_tpl = items.map(item => {
      return <View key={item.id} onClick={this.handelRouter.bind(this, `/pages/legal/detail?id=${item.id}`)} style={_styleSheet["item"]}>
          <Image src={item.logoImg} style={_styleSheet["lawyer-header"]} />
          <View style={_styleSheet["lawyer-info"]}>
            <View style={_styleSheet["line1"]}>
              <Text style={_styleSheet["lawyer-title"]}>{item.name} {item.jobPosition}</Text>
              <Text style={_styleSheet["lawyer-help"]}>已帮助{item.helpAmount}人</Text>
            </View>
            <View style={_styleSheet["line2"]}>
              <Text style={_styleSheet["address"]}>{item.officeAddress}</Text>
            </View>
            <View style={_styleSheet["line3"]}>
              {item.areaName.map(label => {
              return <Text key={label.id} style={_styleSheet["label"]}>{label.title}</Text>;
            })}
            </View>
          </View>
        </View>;
    });
    return <View>
        <View style={_styleSheet["lawyer-wrap"]}>
          <View style={[_styleSheet["select-option"], _styleSheet["pb0"]]}>
            <View style={_styleSheet["option-item"]}>
              <View onClick={this.changeOption.bind(this, 'provinceId', 0, -1)} style={_getStyle(provinceId === -1 ? 'option  option-active' : 'option')}>全部</View>
              <ScrollView scrollX scrollWithAnimation style={_styleSheet["scrollview"]}>
                {allProvince.map((item, index) => {
                return <View key={item.id} onClick={this.changeOption.bind(this, 'provinceId', 0, index)} style={_getStyle(provinceId === index ? 'option  option-active' : 'option')}>{item.label}</View>;
              })}
              </ScrollView>
            </View>

            <View style={[_styleSheet["option-item"], allCity.length <= 0 ? { 'display': 'none' } : '']}>
              <View onClick={this.changeOption.bind(this, 'cityId', 1, -1)} style={_getStyle(cityId === -1 ? 'option  option-active' : 'option')}>全部</View>
              <ScrollView scrollX scrollWithAnimation onScroll={this.onScroll} style={_styleSheet["scrollview"]}>
                {allCity.map((item, index) => {
                return <View key={item.id} onClick={this.changeOption.bind(this, 'cityId', 1, index)} style={_getStyle(cityId === index ? 'option  option-active' : 'option')}>{item.label}</View>;
              })}
              </ScrollView>
            </View>

            <View style={[_styleSheet["option-item"], allDistrict.length <= 0 ? { 'display': 'none' } : '']}>
              <View onClick={this.changeOption.bind(this, 'districtId', 2, -1)} style={_getStyle(districtId === -1 ? 'option  option-active' : 'option')}>全部</View>
              <ScrollView scrollX scrollWithAnimation style={_styleSheet["scrollview"]}>
                {allDistrict.map((item, index) => {
                return <View key={item.value} onClick={this.changeOption.bind(this, 'districtId', 2, index)} style={_getStyle(districtId === index ? 'option  option-active' : 'option')}>{item.label}</View>;
              })}
              </ScrollView>
            </View>
            {areasOfExpertise.length > 0 && <View style={_styleSheet["option-item"]}>
              <View onClick={this.changeLabel.bind(this, null)} style={_getStyle(!labelId ? 'option  option-active' : 'option')}>全部</View>
              <ScrollView scrollX scrollWithAnimation style={_styleSheet["scrollview"]}>
                {areasOfExpertise.map(item => {
                return <View key={item.id} onClick={this.changeLabel.bind(this, item.id)} style={_getStyle(labelId === item.id ? 'option  option-active' : 'option')}>{item.areaName}</View>;
              })}
              </ScrollView>
            </View>}
          </View>

          <View style={_styleSheet["interval"]} />

          {items.length > 0 ? <View style={[_styleSheet["list-2"], _styleSheet["pb0"]]}>{item_tpl}</View> : <View style={_styleSheet["page-footer"]}>没有相关律师信息~</View>}
        </View>
      </View>;
  }
};
Index = tslib_1.__decorate([inject("stores"), observer], Index);
export default Index;